import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login.vue'
import Register from "../components/Register.vue";
import { Message } from 'element-ui';
import ForumIndex from '../components/ForumIndex.vue'
import ForumEdit from '../components/ForumEdit.vue'
import ForumDetails from '../components/ForumDetails.vue'
import AdminIndex from '../components/AdminIndex.vue'
import bannerList from '../components/bannerList.vue';


Vue.use(VueRouter)

const router =  new VueRouter({
  routes:[
    {
      name:'登录',
      path:'/login',
      component:Login,
      meta:{isRequired: false,title:'登录'}
    },
    {
      name:'注册',
      path:'/register',
      component:Register,
      meta:{isRequired: false,title:'注册'}
    },
    {
      name:'论坛主页',
      path:'/index',
      component:ForumIndex,
      meta:{isRequired: true,title:'主页'}
    },
    {
      name:"发表新帖子",
      path:"/EditForum",
      component:ForumEdit,
      meta:{isBan: true,title:'新增'}
    },
    {
      name:"查看单独帖子",
      path:"/ForumDetails/:articleId",
      component:ForumDetails,
      meta:{isRequired: false,title:'查看单独帖子'}
    },
    {
      name:"管理员页面",
      path:"/AdminIndex",
      component:AdminIndex,
      meta:{isAdmin: true,title:'管理员'}
    },
    {
      name:"封禁用户页面",
      path:"/bannerList",
      component:bannerList,
      meta:{isAdmin: true,title:'封禁列表'}
    }
  ]
})

router.beforeEach((to, from, next) => {
  if (to.meta.isRequired) {
    if (sessionStorage.username,sessionStorage.userpassword) {
      next()
    } else {
      Message.warning({
        message: "你还未登录，请先登录"
      })
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    }
  } else {
    next()
  }
})

router.beforeEach((to, from, next) => {
  if (to.meta.isAdmin) {
    if (sessionStorage.useridentity === '2') {
      next()
    } else {
      Message.warning({
        message: "没有管理员账户无法进入"
      })
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    }
  } else {
    next()
  }
})

router.beforeEach((to, from, next) => {
  if (to.meta.isBan) {
    if (sessionStorage.useridentity === '0'|| sessionStorage.useridentity === '2') {
      next()
    } else {
      Message.warning({
        message: "封禁账户无法进入"
      })
      next({
        path: '/index',
        query: { redirect: to.fullPath }
      })
    }
  } else {
    next()
  }
})

export default router